# -*- coding: utf-8 -*-

import sys
from os.path import sep, join, normpath, isdir, isfile
from urlparse import urljoin
import re
from ConfigParser import SafeConfigParser

#config = None

def load_config(path, defaults={}):
    #global config
    cp = SafeConfigParser(defaults)
    cp.read(path)
    #config = ConfigWrapper(cp)
    #config = cp
    return cp

def export_config(environ, cnf):
    environ['renyare.config'] = cnf
    for s in ['paths', 'urls']:
        environ['renyare.%s'% s] = {}
        for o in cnf[s]:
            environ['renyare.%s'% s][o] = cnf[s][o]
    return cnf

class ConfigWrapper(dict):
    """
    Allows retreiving ConfigParser sections and options as instance attributes
    Convenient methods (like `getboolean`) are transferred to section
    >>> from ConfigParser import SafeConfigParser
    >>> from cStringIO import StringIO
    >>> cnf = StringIO('''
    ... [somesection]
    ... someoption1=omg
    ... someoption2=lol
    ... booloption=yes''')
    >>> config = SafeConfigParser()
    >>> config.readfp(cnf)
    >>> config = ConfigWrapper(config)
    >>> print config['somesection']['someoption1']
    omg
    >>> print config['somesection'].getboolean('booloption')
    True
    """
    def __init__(self, config):
        self._config = config
        self._sections = {}

    def __getitem__(self, name):
        if name in self._sections:
            return self._sections[name]
        else:
            self._sections[name] = ConfigSection(self._config, name)
            return self._sections[name]

    def __setitem__(self, name, value):
        raise AttributeError, "Config is read-only when application is running. Please, change config file."

    def __contains__(self, name):
        return name in self._config.sections

    def __iter__(self):
        return self._config.sections.__iter__()

class ConfigSection(dict):
    def __init__(self, config, name):
        self._config = config
        self._name = name

    def __getattr__(self, name):
        if name.startswith('get') and hasattr(self._config, name):
            func = getattr(self._config, name)
            newname = "_"+name
            if not hasattr(self, newname):
                def decorator(item):
                    return func(self._name, item)
                setattr(self, newname, decorator)
            return getattr(self, newname)
        else:
            return getattr(dict, name)

    def __contains__(self, name):
        return name in self._config.hasoption(self._name)

    def __iter__(self):
        return self._config.options(self._name).__iter__()

    def __getitem__(self, name):
        return self._config.get(self._name, name)

    def __setitem__(self, name, value):
        raise AttributeError, "Config is read-only when application is running. Please, change config file."

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()
